﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace XHXTools
{
    /// <summary>
    /// MD5加密工具类
    /// </summary>
    public class MD5Tool
    {
        /// <summary>
        /// MD5（32位加密）
        /// </summary>
        /// <param name="convertString">需要加密的字符串</param>
        /// <returns>返回32位大写加密</returns>
        public static string GetMd5Str32(string convertString)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                MD5 md5 = MD5.Create();
                byte[] bytestr = Encoding.UTF8.GetBytes(convertString);
                byte[] newBuff = md5.ComputeHash(bytestr);
                for (int i = 0; i < newBuff.Length; i++)
                {
                    sb.Append(newBuff[i].ToString("X2").ToUpper());
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// MD5（16位加密）
        /// </summary>
        /// <param name="convertString">需要加密的字符串</param>
        /// <returns>返回16位大写加密</returns>
        public static string GetMd5Str16(string convertString)
        {
            try
            {
                string md5Pwd = string.Empty;
                //使用加密服务提供程序
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                //将指定的字节子数组的每个元素的数值转换为它的等效十六进制字符串表示形式。
                md5Pwd = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(convertString)), 4, 8);
                //去掉“-”
                md5Pwd = md5Pwd.Replace("-", "");
                return md5Pwd;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}
